/*
 * @Author: crissu 13750782397@163.com
 * @Date: 2024-06-04 01:43:52
 * @LastEditors: crissu 13750782397@163.com
 * @LastEditTime: 2024-06-04 01:51:45
 * @FilePath: /try_concurrence/Patterns/BridgeChannel.go
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package patterns

import (
	"fmt"
	"time"
)

func TryBridgeChannel() {
	orDone := func(done, c <-chan interface{}) <-chan interface{} {
		valStream := make(chan interface{})
		go func() {
			defer close(valStream)
			select {
			case <-done:
				fmt.Println("finish")
				return
			case v, ok := <-c:
				if !ok {
					return
				}
				select {
				case <-done:
					return
				case valStream <- v:
				}
			}
		}()
		return valStream
	}

	bridge := func(done <-chan interface{}, chanStream <-chan <-chan interface{}) <-chan interface{} {
		bridgeStream := make(chan interface{})
		go func() {
			defer close(bridgeStream)
			for {
				var stream <-chan interface{}
				select {
				case <-done:
					return
				case maybeStream, ok := <-chanStream:
					if !ok {
						return
					}
					stream = maybeStream
				}
				for val := range orDone(done, stream) {
					select {
					case <-done:
						return
					case bridgeStream <- val:
					}
				}
			}
		}()
		return bridgeStream
	}
	genVals := func() <-chan <-chan interface{} {
		chanStream := make(chan (<-chan interface{}))
		go func() {
			for i := 0; i < 10; i++ {
				stream := make(chan interface{}, 1)
				stream <- i
				close(stream)
				chanStream <- stream
			}
		}()
		return chanStream
	}
	done := make(chan interface{})
	// defer close(done)
	go func() {
		time.Sleep(1 * time.Second)
		close(done)
	}()
	for v := range bridge(done, genVals()) {
		fmt.Printf("%v ", v)
	}
}
